package com.ruoyi.business.alarm.listener;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.business.alarm.constant.DoorAlarmConstants;
import com.ruoyi.business.alarm.domain.DoorStatusInfo;
import com.ruoyi.business.alarm.service.IDoorAlarmLogService;
import com.ruoyi.business.communication.domain.SlotStatus;
import com.ruoyi.business.communication.listener.DeviceStatusListener;
import com.ruoyi.business.device.domain.Device;
import com.ruoyi.common.core.redis.RedisCache;

/**
 * 门报警监听器
 * 监听设备状态更新，当检测到门状态变化时记录报警日志
 * 
 * @author ruoyi
 */
@Component
public class DoorAlarmListener implements DeviceStatusListener {
    
    private static final Logger log = LoggerFactory.getLogger(DoorAlarmListener.class);
    
    @Autowired
    private IDoorAlarmLogService doorAlarmLogService;
    
    @Autowired
    private RedisCache redisCache;

    @Override
    public void onStatusUpdate(Device device, List<SlotStatus> slotStatusList) {
        if (slotStatusList == null || slotStatusList.isEmpty()) {
            return;
        }
        
        try {
            for (SlotStatus slotStatus : slotStatusList) {
                Integer slotNumber = slotStatus.getBusinessSlotNo();
                if (slotNumber == null) {
                    continue;
                }
                
                // 处理电源箱门状态
                Boolean currentPowerBoxOpen = slotStatus.getDoorPowerBoxOpen();
                if (currentPowerBoxOpen != null) {
                    handleDoorStatus(slotNumber, "1", currentPowerBoxOpen, DoorAlarmConstants.REDIS_DOOR_POWER_BOX_KEY);
                }
                
                // 处理槽控机门状态
                Boolean currentControllerOpen = slotStatus.getDoorControllerOpen();
                if (currentControllerOpen != null) {
                    handleDoorStatus(slotNumber, "2", currentControllerOpen, DoorAlarmConstants.REDIS_DOOR_CONTROLLER_KEY);
                }
            }
        } catch (Exception e) {
            log.error("处理门状态更新时发生错误", e);
        }
    }
    
    /**
     * 处理门状态变化
     * 
     * @param slotNumber 槽号
     * @param alarmType 报警类型（1=电源箱门开，2=槽控机门开）
     * @param currentStatus 当前门状态
     * @param redisKeyPrefix Redis键前缀
     */
    private void handleDoorStatus(Integer slotNumber, String alarmType, Boolean currentStatus, String redisKeyPrefix) {
        try {
            // 从Redis获取门状态信息
            String redisKey = redisKeyPrefix + slotNumber;
            DoorStatusInfo doorInfo = redisCache.getCacheObject(redisKey);
            
            Boolean previousStatus = doorInfo != null ? doorInfo.getStatus() : null;
            
            // 判断状态是否发生变化
            if (previousStatus == null || !previousStatus.equals(currentStatus)) {
                // 状态发生变化，更新Redis并处理报警
                log.debug("槽号 {} 的{}门状态发生变化，从 {} 变为 {}", 
                    slotNumber, 
                    alarmType.equals("1") ? "电源箱" : "槽控机",
                    previousStatus,
                    currentStatus);
                if (doorInfo == null) {
                    doorInfo = new DoorStatusInfo();
                }
                doorInfo.setStatus(currentStatus);
                redisCache.setCacheObject(redisKey, doorInfo);
                doorAlarmLogService.handleDoorStatusChange(slotNumber, alarmType, currentStatus, doorInfo);
            }
            // 如果状态没有变化，不处理（避免重复记录）
            
        } catch (Exception e) {
            log.error("处理槽号 {} 的{}门状态时发生错误", 
                slotNumber, 
                alarmType.equals("1") ? "电源箱" : "槽控机", 
                e);
        }
    }
}

